package net.zhengxinyun.performance.controller.indicators;


import com.sirdc.modules.utils.ObjectUtils;
import net.zhengxinyun.performance.Util.StringUtils;
import net.zhengxinyun.performance.Util.Util;
import net.zhengxinyun.performance.core.Result;
import net.zhengxinyun.performance.core.ResultUtils;
import net.zhengxinyun.performance.dto.ExcelDTO;
import net.zhengxinyun.performance.dto.TownDTO;
import net.zhengxinyun.performance.entity.TokenEntity;
import net.zhengxinyun.performance.entity.TownEntity;
import net.zhengxinyun.performance.entity.TownIndicatorsEntity;
import net.zhengxinyun.performance.entity.UserEntity;
import net.zhengxinyun.performance.filter.DepartmentFilter;
import net.zhengxinyun.performance.filter.TownFilter;
import net.zhengxinyun.performance.filter.TownIndicatorsFilter;
import net.zhengxinyun.performance.filter.UserFilter;
import net.zhengxinyun.performance.service.department.DepartmentService;
import net.zhengxinyun.performance.service.exportService.ExcelDtoService;
import net.zhengxinyun.performance.service.exportService.ExportService;
import net.zhengxinyun.performance.service.indicators.TownIndicatorsService;
import net.zhengxinyun.performance.service.indicators.TownScoreService;
import net.zhengxinyun.performance.service.login.LoginService;
import net.zhengxinyun.performance.service.login.TokenService;
import net.zhengxinyun.performance.service.indicators.TownService;
import net.zhengxinyun.performance.service.login.UserService;
import org.apache.catalina.servlet4preview.http.HttpServletRequest;
import org.apache.ibatis.annotations.Param;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import java.io.Serializable;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

/**
 * @Auther: hyp
 * @Date: 2018/10/29 20:28
 */
@RestController
@RequestMapping("/townIndicators")
public class TownIndicatorsController {

    private TownIndicatorsService townIndicatorsService;
    private TownService townService;
    private TokenService tokenService;
    private TownScoreService townScoreService;

    @Autowired
    private ExcelDtoService excelDtoService;

    @Autowired
    private LoginService loginService;

    @Autowired
    private DepartmentService departmentService;

    @Autowired
    private UserService userService;

    @Autowired
    private ExportService excelService;

    @Autowired
    public TownIndicatorsController(TownIndicatorsService townIndicatorsService, TownService townService, TokenService tokenService, TownScoreService townScoreService) {
        this.townIndicatorsService = townIndicatorsService;
        this.townService = townService;
        this.tokenService = tokenService;
        this.townScoreService = townScoreService;
    }

    @PostMapping("/insert")
    public Result<String> insert(@RequestBody TownIndicatorsParam param){
        if (tokenService.compareToken(param.tokenEntity.getValue())){
            if (param.list == null){
                String str = townIndicatorsService.insert(param.townIndicatorsEntity,param.townList);
                if (!"添加成功".equals(str)){
                    return ResultUtils.getResults(Result.Status.ERROR,str);
                }else {
                    return ResultUtils.getSuccessResults();
                }
            }else {
                String datetime  = param.list.get(0).getTownIndicatorsEntity().getDateTime();
                //导入之前先检测是否存在
                String indexType =param.list.get(0).getTownIndicatorsEntity().getIndexType();
                 townIndicatorsService.getIndexByDatetime(datetime,indexType);


                String str = townIndicatorsService.ListInsert(param.list);
                if (!"添加成功".equals(str)){
                    return ResultUtils.getResults(Result.Status.ERROR,str);
                }else {
                    return ResultUtils.getSuccessResults();
                }
            }

        }
        return ResultUtils.getResults(Result.Status.OVERTIME);
    }

    @PostMapping("/delete")
    public Result<String> delete(@RequestBody TownIndicatorsParam param){
        if (tokenService.compareToken(param.tokenEntity.getValue())){
            String str = townIndicatorsService.delete(param.townIndicatorsEntity);
            if (!"删除成功".equals(str)){
                return ResultUtils.getResults(Result.Status.ERROR,str);
            }
            else {
                return ResultUtils.getSuccessResults();
            }
        }

        return ResultUtils.getResults(Result.Status.OVERTIME);
    }

    @PostMapping("/update")
    public Result<String> update(@RequestBody TownIndicatorsParam param){
        if (tokenService.compareToken(param.tokenEntity.getValue())){
           String str = townIndicatorsService.update(param.townIndicatorsEntity,param.townList);
           if (!"更新成功".equals(str)){
               return ResultUtils.getResults(Result.Status.ERROR,str);
           }
           return ResultUtils.getSuccessResults();
        }
        return ResultUtils.getResults(Result.Status.OVERTIME);
    }

    @PostMapping("/query")
    public Result<HashMap<String,Object>> query(@RequestBody TownIndicatorsParam param, HttpServletRequest request){
        TokenEntity token = tokenService.queryByValue(param.tokenEntity.getValue());
        if (tokenService.compareToken(param.tokenEntity.getValue())){
            if (param.townIndicatorsFilter.getPageSize() == 0){
                param.townIndicatorsFilter.setPageSize(10);
            }
            String year=null;
            if(StringUtils.isBlank(param.townIndicatorsFilter.getDateTime()))
            {
                 year = (String) request.getSession().getAttribute("currentYear");
                if(year==null)
                {
                    return ResultUtils.getResults(Result.Status.OVERTIME,"登录超时，请重新登录",null);
                }
                param.townIndicatorsFilter.setDateTime(year);
            }
           // UserEntity userEntity = loginService.getUserByToken(param.tokenEntity);
            UserFilter userFilter = new UserFilter();
            userFilter.setId(token.getUserId());

            List<UserFilter> userEntitys = userService.queryUsers(userFilter);

            UserFilter userEntity = null;
            if(ObjectUtils.isNotBlank(userEntitys)){
                userEntity = userEntitys.get(0);
                userEntity.setUserPermissions(userEntity.getRolePermiss() );
            }

            HashMap<String,Object> map = new HashMap<>();
            TownIndicatorsFilter filter = new TownIndicatorsFilter();
            filter.setIndexType("一级指标");
            filter.setDateTime(year);
            List<TownIndicatorsFilter> firstIndexList = townIndicatorsService.query(filter);
            map.put("firstIndex",firstIndexList);//给一级指标集合
            Double pageTotal = 0.0;
            if ("一级指标".equals(param.townIndicatorsFilter.getIndexType())){
                List<TownIndicatorsFilter>  list =  townIndicatorsService.query(param.townIndicatorsFilter);
                if (list.size()==0){
                    param.townIndicatorsFilter.setPageNumber(param.townIndicatorsFilter.getPageNumber()-1);
                    list = townIndicatorsService.query(param.townIndicatorsFilter);
                }
                map.put("list",list);
                pageTotal = Util.intGetTotalPage(townIndicatorsService.queryForCount(param.townIndicatorsFilter),param.townIndicatorsFilter.getPageSize());
            }else if ("二级指标".equals(param.townIndicatorsFilter.getIndexType())){
                List<Map<String,Object>> secList = townIndicatorsService.querySec(param.townIndicatorsFilter,userEntity);
                if (secList.size() == 0){
                    param.townIndicatorsFilter.setPageNumber(param.townIndicatorsFilter.getPageNumber()-1);
                    secList = townIndicatorsService.querySec(param.townIndicatorsFilter,userEntity);
                }


                map.put("list",secList);
                pageTotal = Util.intGetTotalPage(townIndicatorsService.queryForCount(param.townIndicatorsFilter),param.townIndicatorsFilter.getPageSize());
            }
            map.put("pageTotal",pageTotal);
            return ResultUtils.getSuccessResults(map);
        }
        return ResultUtils.getResults(Result.Status.OVERTIME,"token不对",null);
    }


    /**
     * 导入市对县的指标
     * @param file
     * @return
     */
    @PostMapping("/uploadTownIndex")
    public Result<HashMap<String,Object>> uploadTownIndex(@RequestParam(value = "file") MultipartFile file)
    {
        if(file ==null)
        {
            return ResultUtils.getResults(Result.Status.ERROR, "上传失败，上传文件不能为空", null);
        }
        String fileName = file.getOriginalFilename();

        if(!fileName.matches("^.+\\.(?i)(xls)$")&&!fileName.matches("^.+\\.(?i)(xlsx)$")){
            return ResultUtils.getResults(Result.Status.ERROR, "上传失败，文件格式错误",null);
        }


        HashMap<String,Object> map  =  excelService.uploadTownIndex(file);
        if((int) map.get("code")==200)
        {
            return ResultUtils.getSuccessResults(map);
        }else {
            return  ResultUtils.getResults(Result.Status.ERROR, map.get("message")+"",null);
        }


    }



    //导入数据校验后的查询
    @PostMapping("/queryImport")
    public Result<HashMap<String, Object>> queryData(@RequestBody TownIndicatorsParam param )
    {
        if(ObjectUtils.isBlank(param.excelDTO))
        {
            return ResultUtils.getResults(Result.Status.ERROR, "KeyOne为空", null);
        }
        String batchNum = param.excelDTO.getBatchNum();

        if(StringUtils.isBlank(batchNum))
        {
            return ResultUtils.getResults(Result.Status.ERROR, "导入批次号为空", null);
        }

        List<ExcelDTO> dtoList = excelDtoService.queryData(batchNum,null);
        List<ExcelDTO> collect = dtoList.stream().filter(dto -> 0==dto.getAvail()).collect(Collectors.toList());
        HashMap<String,Object> map = new HashMap<>();
        map.put("list",dtoList);
        if (collect.size()>0){
            map.put("warn","当前数据有"+collect.size()+"条警告信息。");
        }else {
            map.put("warn","校验通过，无警告数据，可直接上传数据");
        }
        return ResultUtils.getSuccessResults(map);
    }
    @PostMapping("/updateExcelData")
    public Result<HashMap<String,Object>>  updateExcelData(@RequestBody TownIndicatorsParam param)
    {
        Long id = param.excelDTO.getId();
        String batchNum = param.excelDTO.getBatchNum();
        if(ObjectUtils.isBlank(id))
        {
            return ResultUtils.getResults(Result.Status.ERROR, "Id为空，请重新操作", null);
        }
        int i=  excelDtoService.updateExcelData(param.excelDTO);
        if(i==0)
        {
            return ResultUtils.getResults(Result.Status.ERROR, "操作失败", null);
        }
        List<ExcelDTO> dtoList = excelDtoService.queryData(batchNum,null);
        List<ExcelDTO> collect = dtoList.stream().filter(dto -> 0==dto.getAvail()).collect(Collectors.toList());
        HashMap<String,Object> map = new HashMap<>();
        map.put("list",dtoList);
        if (collect.size()>0){
            map.put("warn","当前数据有"+collect.size()+"条警告信息。");
        }else {
            map.put("warn","校验通过，无警告数据，点击‘确认导入’按钮直接上传数据");
        }
        return ResultUtils.getSuccessResults(map);
    }


    /**
     * 保存导入
     * @param param
     * @return
     */
    @PostMapping("/saveExcelData")
    public Result<String> saveExcelData(@RequestBody TownIndicatorsParam param)
    {
        String batchNum = param.excelDTO.getBatchNum();
        String datetime = param.excelDTO.getDatetime();
        if(StringUtils.isBlank(batchNum)|| StringUtils.isBlank(datetime))
        {
            return  ResultUtils.getResults(Result.Status.ERROR,"批次号或者导入日期为空，请重新操作");
        }
        List<ExcelDTO> dtoList = excelDtoService.queryData(batchNum,1);

        int i =townIndicatorsService.saveExcelDate(dtoList,datetime);
        if(i==0)
        {
            return  ResultUtils.getResults(Result.Status.ERROR,"导入失败，请根据导入批次号联系管理员");
        }

        return  ResultUtils.getSuccessResults();

    }




}

class TownIndicatorsParam{
    public TownIndicatorsFilter townIndicatorsFilter;
    public TownIndicatorsEntity townIndicatorsEntity;
    public ExcelDTO excelDTO;
    public TokenEntity tokenEntity;
    public List<TownEntity> townList;
    public TownEntity townEntity;
    public TownFilter townFilter;
    public List<TownDTO> list;
    public TownDTO townDTO;
}
